package com.example.remoteassistance;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.media.projection.MediaProjectionManager;
import android.os.Bundle;
import android.os.IBinder;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.Toast;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.HashMap;
import java.util.Map;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;

//录屏活动
public class RecordActivity extends AppCompatActivity implements View.OnClickListener{
    
    private static final String TAG = "RecordActivity";

    private static final int MEDIAPROJECTION_REQUEST_CODE = 1;

    private Button mRecordSwitch;

    private static boolean isRecord = false;

    private String mid;
    private String sid;

    private MessageWebSocketClient mMessageWebSocketClient;
    private MessageWebSocketService mMessageWebSocketService;
    private final ServiceConnection mMessageWebSocketServiceConnection = new ServiceConnection() {
        //绑定数据传输websocket服务
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            mMessageWebSocketService = ((MessageWebSocketService.MessageWebSocketBinder) iBinder).getService();
            mMessageWebSocketClient = MessageWebSocketService.mMessageWebSocketClient;
            Log.d(TAG, "onServiceConnected");
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            if (mMessageWebSocketService != null) {
                mMessageWebSocketService = null;
            }
            Log.d(TAG, "onServiceDisconnected");
        }
    };

    private StreamWebSocketService mStreamWebSocketService;
    private final ServiceConnection mStreamWebSocketServiceConnection = new ServiceConnection() {
        //绑定视频流传输websocket服务
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            mStreamWebSocketService = ((StreamWebSocketService.StreamWebSocketBinder) iBinder).getService();
            Log.d(TAG, "onServiceConnected");
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            if (mStreamWebSocketService != null) {
                mStreamWebSocketService = null;
            }
            Log.d(TAG, "onServiceDisconnected");
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_record);

        //导航栏返回按键
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setTitle("返回");
            actionBar.setDisplayHomeAsUpEnabled(true);
        }

        //通过intent获取主机和从机id
        Intent intent = getIntent();
        setMid(intent.getStringExtra("mid"));
        setSid(intent.getStringExtra("sid"));

        //绑定数据传输websocket服务
        bindMessageWebSocketService();
        //请求录屏权限
        requestMediaProjectionPermission();
        //初始化界面
        initViews();
    }

    //导航栏返回按键点击 返回主界面
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            startActivity(new Intent(this, MainActivity.class));
            this.finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mStreamWebSocketService.destroyRecord();
        Log.d(TAG, "onDestroy");
    }

    //绑定数据传输websocket服务
    private void bindMessageWebSocketService() {
        Intent intent = new Intent(RecordActivity.this, MessageWebSocketService.class);
        intent.putExtra("mid", getMid());
        bindService(intent, mMessageWebSocketServiceConnection, BIND_AUTO_CREATE);
    }

    //绑定视频流传输websocket服务
    private void bindStreamWebSocketService(int resultCode, Intent data) {
        Bundle bundle = new Bundle();
        bundle.putInt("code", resultCode);
        bundle.putParcelable("data", data);
        bundle.putString("mid", getMid()+"-stream");
        Intent intent = new Intent(RecordActivity.this, StreamWebSocketService.class);
        intent.putExtras(bundle);
        bindService(intent, mStreamWebSocketServiceConnection, BIND_AUTO_CREATE);
    }

    //初始化界面
    private void initViews() {
        mRecordSwitch = (Button) findViewById(R.id.record_switch);
        mRecordSwitch.setOnClickListener(this);
    }

    private void setMid(String mid) {
        this.mid = mid;
    }

    private String getMid() {
        return mid;
    }

    private void setSid(String sid) {
        this.sid = sid;
    }

    private String getSid() {
        return sid;
    }


    //申请录屏权限
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == MEDIAPROJECTION_REQUEST_CODE) {
            if (resultCode != RESULT_OK) {
                Toast.makeText(this, "MediaProjection 权限申请失败", Toast.LENGTH_SHORT).show();
                return;
            }
            //绑定视频流传输websocket服务
            bindStreamWebSocketService(resultCode, data);
        }
    }

    //请求录屏权限
    private void requestMediaProjectionPermission() {
        MediaProjectionManager mediaProjectionManager = (MediaProjectionManager) this.getSystemService(Context.MEDIA_PROJECTION_SERVICE);
        Intent intent = mediaProjectionManager.createScreenCaptureIntent();
        startActivityForResult(intent, MEDIAPROJECTION_REQUEST_CODE);
    }

    @Override
    public void onClick(View view) {
        //录屏按钮事件
        if (view.getId() == R.id.record_switch) {
            if (!isRecord) {
                isRecord = true;
                //发送录屏屏幕尺寸
                sendRecordScreenSize();
                mStreamWebSocketService.startRecord();
                mRecordSwitch.setText("停 止");
            } else {
                isRecord = false;
                mStreamWebSocketService.stopRecord();
                mRecordSwitch.setText("开 始");
            }
        }
    }

    //获取屏幕尺寸
    private Map<String, Integer> getScreenSize() {
        WindowManager windowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics metrics = new DisplayMetrics();
        windowManager.getDefaultDisplay().getRealMetrics(metrics);
        Map<String, Integer> size = new HashMap<String, Integer>();
        size.put("width", metrics.widthPixels);
        size.put("height", metrics.heightPixels);
        return size;
    }

    //发送录屏屏幕尺寸
    public void sendRecordScreenSize() {
        ObjectMapper mapper = new ObjectMapper();
        MessagePacket packet = new MessagePacket();
        Map<String, Integer> size = getScreenSize();
        String msg = null;
        packet.setMsg("size");
        packet.setMid(getMid());
        packet.setSid(getSid());
        packet.setMap(size);
        try {
            msg = mapper.writeValueAsString(packet);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        mMessageWebSocketClient.send(msg);
    }
}
